package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * 105. 从前序与中序遍历序列构造二叉树
 * 剑指 Offer 07. 重建二叉树
 *
 * @Author liw
 * @Date 2021/4/28 14:01
 * @Version 1.0
 */
public class BuildTree {


    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        int length = preorder.length - 1;
        TreeNode node = new TreeNode(preorder[0]);
        find(preorder, inorder, node, 0, length, 0, length);
        return node;
    }

    private void find(int[] preorder, int[] inorder, TreeNode node, int st, int end, int st2, int end2) {
        if (st > end) {
            return;
        }
        int value = preorder[st];
        int split = st2;
        for (int j = st2; j <= end2; j++) {
            if (inorder[j] == value) {
                split = j;
                break;
            }
        }
        int leftLength = split - st2;
        if (leftLength != 0) {
            TreeNode l = new TreeNode(preorder[st + 1]);
            node.left = l;
            find(preorder, inorder, l, st + 1, st + leftLength, st2, split - 1);
        }
        if (split != end2) {
            TreeNode r = new TreeNode(preorder[st + 1 + leftLength]);
            node.right = r;
            find(preorder, inorder, r, st + 1 + leftLength, end, split + 1, end2);
        }
    }


}
